package site.brood.common.security.service;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import site.brood.common.core.id.IdUtil;
import site.brood.common.core.ip.IpUtil;
import site.brood.common.core.jwt.JwtUtil;
import site.brood.common.core.str.StrUtil;
import site.brood.common.core.time.TimeUtil;
import site.brood.common.core.web.ServletUtil;
import site.brood.common.core.constant.Constants;
import site.brood.common.core.user.LoginUserVO;
import site.brood.common.redis.service.RedisService;
import site.brood.common.security.util.SecurityUtil;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * token验证处理
 *
 * @author ruoyi
 */
@Component
public class TokenService
{
    @Autowired
    private RedisService redisService;

    protected static final long MILLIS_SECOND = 1000;

    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

    private final static long expireTime = Constants.CACHE_EXPIRATION;

    private final static String ACCESS_TOKEN = Constants.CACHE_LOGIN_TOKEN_KEY_PREFIX;

    private final static Long MILLIS_MINUTE_TEN = Constants.CACHE_REFRESH_TIME * MILLIS_MINUTE;

    /**
     * 创建令牌
     */
    public Map<String, Object> createToken(LoginUserVO loginUserVO)
    {
        String cacheKey = IdUtil.fastUUID();
        Long userId = loginUserVO.getId();
        String name = loginUserVO.getUsername();
        loginUserVO.setCacheKey(cacheKey);
        loginUserVO.setId(userId);
        loginUserVO.setUsername(name);
        loginUserVO.setLoginIp(IpUtil.getIpAddr(ServletUtil.getRequest()));
        //将用户详情写入redis
        refreshToken(loginUserVO);

        // Jwt存储信息
        Map<String, Object> claimsMap = new HashMap<String, Object>();
        claimsMap.put(Constants.JWT_USER_CACHE_KEY, cacheKey);
        claimsMap.put(Constants.JWT_USER_ID, userId);
        claimsMap.put(Constants.JWT_USER_NAME, name);

        // 接口返回信息
        Map<String, Object> rspMap = new HashMap<String, Object>();
        rspMap.put("access_token", JwtUtil.createToken(claimsMap));
        rspMap.put("expires_in", expireTime);
        return rspMap;
    }

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUserVO getLoginUser()
    {
        return getLoginUser(ServletUtil.getRequest());
    }

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUserVO getLoginUser(HttpServletRequest request)
    {
        // 获取请求携带的令牌
        String token = SecurityUtil.getToken(request);
        return getLoginUser(token);
    }

    /**
     * 从redis中取出用户详情信息
     * @return 用户信息
     */
    public LoginUserVO getLoginUser(String token)
    {
        LoginUserVO user = null;
        try
        {
            if (StrUtil.isNotEmpty(token))
            {
                String userkey = JwtUtil.getUserCacheKey(token);
                user = redisService.getCacheObject(getFullCacheKey(userkey));
                return user;
            }
        }
        catch (Exception e)
        {
        }
        return user;
    }

    /**
     * 设置用户身份信息
     */
    public void setLoginUser(LoginUserVO loginUserVO)
    {
        if (StrUtil.isNotNull(loginUserVO) && StrUtil.isNotEmpty(loginUserVO.getCacheKey()))
        {
            refreshToken(loginUserVO);
        }
    }

    /**
     * 删除用户缓存信息
     */
    public void delLoginUser(String token)
    {
        if (StrUtil.isNotEmpty(token))
        {
            String userCachekey = JwtUtil.getUserCacheKey(token);
            redisService.deleteObject(getFullCacheKey(userCachekey));
        }
    }

    /**
     * 验证令牌有效期，相差不足120分钟，自动刷新缓存
     *
     * @param loginUserVO
     */
    public void verifyToken(LoginUserVO loginUserVO)
    {
        long expireTime = TimeUtil.time2MiliSecond(loginUserVO.getExpireTime());
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN)
        {
            refreshToken(loginUserVO);
        }
    }

    /**
     * 刷新令牌有效期
     *
     * @param loginUserVO 登录信息
     */
    public void refreshToken(LoginUserVO loginUserVO)
    {
        loginUserVO.setLoginDate(TimeUtil.getNowDateTime());
        loginUserVO.setExpireTime(loginUserVO.getLoginDate().plusMinutes(expireTime * MILLIS_MINUTE));
        // 根据uuid将loginUser缓存
        String userCacheKey = getFullCacheKey(loginUserVO.getCacheKey());
        redisService.setCacheObject(userCacheKey, loginUserVO, expireTime, TimeUnit.MINUTES);
    }

    private String getFullCacheKey(String token)
    {
        return ACCESS_TOKEN + token;
    }
}
